/**
 * 
 */
package com.wolfpire.proms.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.wolfpire.proms.model.ProjectIndex;
import com.wolfpire.proms.service.ProjectIndexService;
import com.wolfpire.system.common.AuthorityUtils;
import com.wolfpire.system.common.Constants;
import com.wolfpire.system.common.EasyuiPage;
import com.wolfpire.system.common.EasyuiPagination;
import com.wolfpire.system.common.Page;
import com.wolfpire.system.common.Result;
import com.wolfpire.system.common.springmvc.PrincipalArgument;
import com.wolfpire.system.model.Attachment;
import com.wolfpire.system.model.Authority;
import com.wolfpire.system.model.User;
import com.wolfpire.system.service.AttachmentService;

/**
 * 项目指标控制器
 * @author lihd
 *
 */

@Controller
@RequestMapping("/projectIndex")
public class ProjectIndexController {
	
	@Resource private ProjectIndexService projectIndexService;
	
	@Resource private AttachmentService attachmentService;
	
	@RequestMapping("/list")
	public ModelAndView list(@PrincipalArgument User user, @RequestParam Long menuId) {
		//获取对应菜单的操作权限
//		List<Authority> operAuthorities = getAperAuthorities(user, menuId);
		List<Authority> operAuthorities = AuthorityUtils.getAperAuthorities(user, menuId);
		return new ModelAndView("proms/projectindex/projectindex_list", "operAuthorities", operAuthorities);
	}
	
	@ResponseBody
	@RequestMapping("/queryList")
	public EasyuiPagination<ProjectIndex> queryList(EasyuiPage<ProjectIndex> page, ProjectIndex filterProjectIndex) {
		Page<ProjectIndex> projectIndexs = this.projectIndexService.setPageDataList(page, filterProjectIndex);
		return new EasyuiPagination<ProjectIndex>(projectIndexs );
	}
	
	@ResponseBody
	@RequestMapping("/projectIndexs")
	public List<ProjectIndex> projectIndexs(ProjectIndex projectIndex) {
		if (null != projectIndex && null != projectIndex.getId()) {
			projectIndex.setParentId(projectIndex.getId());
			projectIndex.setId(null);
		}
		return this.projectIndexService.list(projectIndex);
	}
	
	@RequestMapping(value = "/add")
	public ModelAndView add(HttpSession session, ProjectIndex projectIndex) {
		ModelAndView mv = new ModelAndView("proms/projectindex/projectindex_add");
		mv.addObject(projectIndex);
		return mv;
	}
	
	@RequestMapping(value = "/edit")
	public ModelAndView edit(Long id) {
		ModelAndView mv = new ModelAndView("proms/projectindex/projectindex_edit");
		if (null != id) {
			ProjectIndex projectIndex = this.projectIndexService.getRoleInfoProjectIndex(id);
			mv.addObject(projectIndex);
		}
		return mv;
	}
	
	@RequestMapping(value = "/detail")
	public ModelAndView detail(Long id) {
		ModelAndView mv = new ModelAndView("proms/projectindex/projectindex_detail");
		if (null != id) {
			ProjectIndex projectIndex = this.projectIndexService.getRoleInfoProjectIndex(id);
			mv.addObject(projectIndex);
		}
		return mv;
	}
	
	@ResponseBody
	@RequestMapping("/save")
	public Result save(ProjectIndex projectIndex) {
		try {
			this.projectIndexService.saveOrUpdate(projectIndex);
			return new Result(true, "保存成功");
		} catch (Exception e) {
			e.printStackTrace();
			return new Result(false, "保存失败，请联系管理员");
		}
	}
	
	@ResponseBody
	@RequestMapping("/delete")
	public Result delete(@RequestParam(value="id")Long id) {
		try {
			this.projectIndexService.del(id);
			return new Result(true, "删除成功");
		} catch (Exception e) {
			e.printStackTrace();
			return new Result(false, "删除失败");
		}
	}
	
	@RequestMapping("/attas")
	public ModelAndView attas(@PrincipalArgument User user, @RequestParam Long menuId) {
		//获取对应菜单的操作权限
//		List<Authority> operAuthorities = getAperAuthorities(user, menuId);
		List<Authority> operAuthorities = AuthorityUtils.getAperAuthorities(user, menuId);
		return new ModelAndView("proms/projectindex/projectindex_attas", "operAuthorities", operAuthorities);
	}
	
	@ResponseBody
	@RequestMapping("/attasList")
	public EasyuiPagination<Map<String, Object>> attasList(
			EasyuiPage<Map<String, Object>> page,
			@RequestParam(value = "projectIndexId", required = false) Long projectIndexId,
			Attachment filterAttachment) {
		Page<Map<String, Object>> attachments = this.attachmentService.setAttachmentsByPiId(page, projectIndexId, filterAttachment);
		return new EasyuiPagination<Map<String, Object>>(attachments);
	}
	
	@RequestMapping(value = "/addAttas")
	public ModelAndView addAttas(HttpSession session, ProjectIndex projectIndex) {
		ModelAndView mv = new ModelAndView("proms/projectindex/projectindex_add_attas");
		mv.addObject(projectIndex);
		return mv;
	}
	
	@ResponseBody
	@RequestMapping("/saveAttas")
	public Result saveAttas(ProjectIndex projectIndex) {
		try {
			this.projectIndexService.batchRelateAttachment(projectIndex);
			return Result.SUCCESS;
		} catch (Exception e) {
			e.printStackTrace();
			return Result.FAILURE;
		}
	}
	
	/***验收材料模块**/
	@RequestMapping("/acceptanceAttas")
	public ModelAndView acceptanceAttas(@PrincipalArgument User user, @RequestParam Long menuId) {
		//获取对应菜单的操作权限
		List<Authority> operAuthorities = AuthorityUtils.getAperAuthorities(user, menuId);
		return new ModelAndView("proms/projectindex/projectindex_acceptanceAttas", "operAuthorities", operAuthorities);
	}
	
	@ResponseBody
	@RequestMapping("/acceptanceAttasList")
	public EasyuiPagination<Map<String, Object>> acceptanceAttasList(
			EasyuiPage<Map<String, Object>> page,
			@RequestParam(value = "projectIndexId", required = false) Long projectIndexId,
			Attachment filterAttachment) {
		Page<Map<String, Object>> attachments = this.attachmentService.setAcceptanceAttachmentsByPiId(page, projectIndexId, filterAttachment);
		return new EasyuiPagination<Map<String, Object>>(attachments);
	}
	
	@RequestMapping(value = "/addAcceptanceAttas")
	public ModelAndView addAcceptanceAttas(HttpSession session, ProjectIndex projectIndex) {
		ModelAndView mv = new ModelAndView("proms/projectindex/projectindex_add_acceptanceAttas");
		projectIndex = this.projectIndexService.get(projectIndex.getId());
		mv.addObject(projectIndex);
		return mv;
	}
	
	@ResponseBody
	@RequestMapping("/saveAcceptanceAttas")
	public Result saveAcceptanceAttas(
			HttpSession session, 
			@RequestParam(value = "selectProcessIds", required = false) String selectProcessIds,
			ProjectIndex projectIndex) {
		try {
			
			// 绑定上传的验收材料
			this.projectIndexService.batchRelateAttachment(projectIndex);
			// 佐证材料转换成验收材料
			if (StringUtils.isNotBlank(selectProcessIds)) {
				String[] processAttaIds = selectProcessIds.split(",");
				List<Long> attaIds = new ArrayList<Long>();
				for (int i = 0; i < processAttaIds.length; i++) {
					attaIds.add(Long.parseLong(processAttaIds[i]));
				}
				List<Attachment> attas = this.attachmentService.getById(attaIds.toArray(new Long[attaIds.size()]));
				String rootPath = Constants.FILE_ROOT_PATH;
				for (Attachment atta : attas) {
					// 1.复制到新的目录去
					String filePath = atta.getFilePath();
					String oldPath = rootPath + File.separator + atta.getFilePath();
					String extName = filePath.substring(filePath.lastIndexOf("."), filePath.length());
					String tempPath =  "upload" + File.separator + "atta" + File.separator + new SimpleDateFormat("yyyyMMdd").format(new Date()) + File.separator + System.currentTimeMillis() + extName;
					String newPath = rootPath + File.separator + tempPath;
					this.copyFile(oldPath, newPath);
					// 2.绑定附件表关系
					Attachment att = new Attachment();
					att.setAttaType("projectIndex_acceptance");
					att.setBizId(projectIndex.getId());
					att.setCreateTime(atta.getCreateTime());
					att.setDownCount(atta.getDownCount());
					att.setFileContent(atta.getFileContent());
					att.setFileName(atta.getFileName());
					att.setFilePath(tempPath);
					att.setFileSize(atta.getFileSize());
					att.setTitle(atta.getTitle());
					this.attachmentService.save(att);
				}
			}

			return Result.SUCCESS;
		} catch (Exception e) {
			e.printStackTrace();
			return Result.FAILURE;
		}
	}
	
	@ResponseBody
	@RequestMapping("/relationToAcceptanceAttas")
	public Result relationToAcceptanceAttas(HttpSession session, ProjectIndex projectIndex) {
		try {
			this.projectIndexService.batchRelateAttachment(projectIndex);
			return Result.SUCCESS;
		} catch (Exception e) {
			e.printStackTrace();
			return Result.FAILURE;
		}
	}
	
	public void copyFile(String oldPath, String newPath) throws IOException {
		@SuppressWarnings("unused")
		int bytesum = 0;
		int byteread = 0;
		File oldfile = new File(oldPath);
		System.out.println("源路径:" + oldPath);
		System.out.println("目标路径:" + newPath);
		if (oldfile.exists()) { // 文件存在时
			InputStream inStream = new FileInputStream(oldPath); // 读入原文件
			FileOutputStream fs = new FileOutputStream(newPath);
			byte[] buffer = new byte[1444];
			while ((byteread = inStream.read(buffer)) != -1) {
				bytesum += byteread; // 字节数 文件大小
				fs.write(buffer, 0, byteread);
			}
			inStream.close();
		} else {
			System.out.println("源文件:" + oldPath + "不存在");
		}
	}
	
	@RequestMapping("/budget")
	public ModelAndView budget(@PrincipalArgument User user, @RequestParam Long menuId) {
		//获取对应菜单的操作权限
//		List<Authority> operAuthorities = getAperAuthorities(user, menuId);
		List<Authority> operAuthorities = AuthorityUtils.getAperAuthorities(user, menuId);
		return new ModelAndView("proms/projectindex/budget", "operAuthorities", operAuthorities);
	}
	
	@ResponseBody
	@RequestMapping("/budgetModifySave")
	public Result budgetModifySave(HttpSession session, ProjectIndex p) {
		try {
			String[] ps = p.getRemark().split(";");
			List<ProjectIndex> list = new ArrayList<ProjectIndex>();
			for(int i=0;i<ps.length;i++){
				String signal = ps[i];
				if(!signal.equals("")){
					ProjectIndex pi = new ProjectIndex();
					pi.setId(Long.valueOf(signal.split(",")[0]));
					pi.setPlanAmount(signal.split(",")[1]);
					list.add(pi);
				}
			}
			projectIndexService.batchModifyBudget(list);
			return Result.SUCCESS;
		} catch (Exception e) {
			e.printStackTrace();
			return Result.FAILURE;
		}
	}
}
